<?php

namespace App\Http\Controllers\Live;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Http\Service\OSSClient\QiniuyunOSSClientService;
use App\Jobs\liveRecordFileDealWithTask;

class LiveRecordController extends BaseController{

    private String $recordDir;

    public function __construct() {
        parent::__construct();
        $this->recordDir = config("env.live_record_dir", "bililive-recorder");
    }

    public function LiveStatusChange(Request $request) {
        $input = $request->all();
        Log::info('live status change event:' . $input['EventType']);
        if(!empty($input['EventType']) && !empty($input['EventData'])) {
            $eventData = $input['EventData'];
            $data = [
                "roomId" => $eventData['RoomId'],
                "shortId" => $eventData['ShortId'],
                "anchorName" => $eventData['Name'],
                "liveTitle" => $eventData['Title']
            ];

            switch ($input['EventType']) {
                case "SessionStarted":
                    break;
                case "FileOpening":
                    Log::info('live record file start');
                    break;
                case "FileClosed":
                    Log::info('live record file close');
                    $data = array_merge($data, [
                        "relativePath" => $eventData['RelativePath']
                    ]);
                    $this->fileClosedEvent($data);
                    break;
                case "SessionEnded":
                    break;
                case "StreamStarted":
                    break;
                case "StreamEnded":
                    break;
            }
        }
        return $this->returnJson([], "success");
    }

    private function fileClosedEvent($data) {
        $filePath = "/" . trim($this->recordDir, "/") . "/" . trim($data['relativePath'], "/");
        $config = [
            "key" => "bili-live-record/" . $data['relativePath'],
            "filePath" => $filePath
        ];
        Log::info('add live record file deal with task: ' . $config['filePath']);
        liveRecordFileDealWithTask::dispatch($config)->onQueue('liveRecordFileDealWithTask');
    }
}
